package org.clipjoint.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 	数据源工具类
 * @author duanzx
 *
 */
public final class DataSourceUtil {
	
	private DataSourceUtil() {};
	
	private static DataSource dataSource = null;
	
	static {
		// 1.加载配置文件
		Properties properties = new Properties();
		try {
			properties.load(DataSourceUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		// 2.创建数据源对象
		try {
			dataSource = DruidDataSourceFactory.createDataSource(properties);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// 获取数据库连接对象
	public static Connection getConnection() {
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 获取数据库连接池对象
	public static DataSource getDataSource() {
		return dataSource;
	}
	
	// 释放资源
	public static void close(ResultSet rs, Statement stmt, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	

}
